package cn.source.system.common.aop.operation;

import cn.hutool.core.map.MapUtil;
import cn.source.system.common.Util.IpAddressUtil;
import cn.source.system.common.annotation.Operation;
import cn.source.system.operation.entity.SystemOperationLog;
import cn.source.system.operation.service.SystemOperationLogService;
import cn.source.system.organization.entity.User;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 切面处理类，操作日志异常日志记录处理
 *
 * @Author YXZhou
 */
@Aspect
@Component
@Slf4j
public class OperationLogAspect {


    @Resource
    private SystemOperationLogService operationLogService;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(cn.source.system.common.annotation.Operation)")
    public void operLogPoinCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) throws IOException {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        // 获取用户
        User user = (User) request.getSession().getAttribute("user");
        //获取请求ip
        String ip = IpAddressUtil.getIpAddress(request);

        SystemOperationLog systemOperationLog = new SystemOperationLog();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            Operation opLog = method.getAnnotation(Operation.class);
            if (opLog != null) {
                String operModul = opLog.operModul();
                String operType = opLog.operType();
                String operDesc = opLog.operDesc();
                systemOperationLog.setOperationModule(operModul);
                systemOperationLog.setOperationType(operType);
                systemOperationLog.setOperationDesc(operDesc);
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            systemOperationLog.setOperationMethod(methodName);
            //获取用户请求方法的参数并序列化为JSON格式字符串
            String params = getRequestParam(joinPoint, request);
            systemOperationLog.setOperationRequestParam(params);
            systemOperationLog.setOperationResponseParam(JSON.toJSONString(keys));
            if (user != null) {
                systemOperationLog.setOperationUserName(user.getUserName());
                systemOperationLog.setOperationTrueName(user.getTrueName());
            }
            systemOperationLog.setOperationIp(ip);
            systemOperationLog.setOperationUri(request.getRequestURI());
            systemOperationLog.setOperationCreateTime(new Date());
            operationLogService.save(systemOperationLog);
        } catch (Exception e) {
            log.error("拦截用户系统操作日志异常{}", e);
        }
    }

    /**
     * 转换request 请求参数
     *
     * @param joinPoint
     */
    public String getRequestParam(JoinPoint joinPoint, HttpServletRequest request) {
        Map<String, Object> param = new HashMap<>(16);
        Enumeration enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paraName = (String) enu.nextElement();
            param.put(paraName, request.getParameter(paraName));
        }
        if (MapUtil.isEmpty(param)) {
            StringBuilder params = new StringBuilder();
            Object[] args = joinPoint.getArgs();
            System.out.println(args);
            if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
                for (int i = 0; i < joinPoint.getArgs().length; i++) {
                    params.append(JSONObject.toJSONString(joinPoint.getArgs()[i]) + ";");
                }
            }
            if ("".equals(params.toString())) {
                return "";
            }
            return params.toString().substring(0, params.length() - 1);
        } else {
            return JSONObject.toJSONString(param);
        }
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}
